package fmt

import (
	"fmt"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnSprintf{})
	if err != nil {
		panic(err)
	}
}

type fnSprintf struct {}

func (fnSprintf) Name() string {
	return "sprintf"
}

func (fnSprintf) Sig() (params []data.Type, isVariadic bool) {
	return []data.Type{data.TypeString, data.TypeAny}, true
}

func (fnSprintf) Eval(params ...interface{}) (interface{}, error) {
	if len(params) < 1 {
		return nil, fmt.Errorf("expect at least 1 argument")
	}
	format, err := coerce.ToString(params[0])
	if err != nil {
		return nil, err
	}
	res := fmt.Sprintf(format, params[1:]...)
	return res, nil
}
